import { Component, OnInit, ViewChild } from '@angular/core';
import {   ActionSheetController, AlertController,  IonTabs, MenuController, NavController,   PopoverController} from '@ionic/angular';
import { LoginInfoService } from '../../../services/login-info.service';
import { LoginPage} from '../../login/login.page';
import { ModalController} from '@ionic/angular';
import {EventService  } from '../../../services/QaService';
import { commService} from '../../../services/comm.service';
import { HttpService } from '../../../services/http.service';
@Component({
  selector: 'page-tabs',
  templateUrl: 'tabs.page.html',
  styleUrls: ['tabs.page.scss']
})
export class TabsPage {
  @ViewChild('tabs', { static: true }) tabs: IonTabs;
  tabsCanGoBack = false;
  tabsParentCanGoBack = false;
  public loginN:any;
  public firstLoginFlag="";
  public firstLoginFlag2="3";
  public next=1;
  public isShow=true;
  public isProgress = false;
  public appContent = '';
  public apkUrl = '';
  constructor(
    public LoginInfoService:LoginInfoService,
    public modalController: ModalController, 
    public eventService:EventService ,
    public commService:commService,
    public modalCtrl: ModalController,
    public alertCtrl: AlertController,
    public actionSheetCtrl: ActionSheetController,
    public popoverCtrl: PopoverController,
    public menuCtrl: MenuController,
    public nav: NavController,
    public httpService: HttpService,
    public alertController: AlertController
  ) {
  
  }
  public flag = 'tab1';

  ngOnInit(): void {
    // window['androidObj'].loadMainUIOver();
    // this.firstLoginFlag=this.LoginInfoService.getlocal('firstLoginFlag') || "1";//设置是否第一展示提示屏幕
    this.firstLoginFlag2=this.LoginInfoService.getlocal('firstLoginFlag2') || "3";//设置是否第一展示提示屏幕
    this.eventService.eventEmitter.on('userInfo',()=>{
      setTimeout(()=>{
        this.loginOut();
      },300)
    })


    this.commService.onAndroidBack().subscribe(res=>{
      this.tabsCanGoBack = this.tabs.outlet.canGoBack();
      console.log(this.tabsCanGoBack)
      this.tabsParentCanGoBack = this.tabs.outlet.parentOutlet.canGoBack();
      console.log(this.tabsParentCanGoBack)
      this.androidBackButtonHandle();
    })
  }

  async androidBackButtonHandle() {
    this.nav.pop();
    try {
        const alert = await this.alertCtrl.getTop();
        console.log("alert"+alert)
        if (alert) {
            alert.dismiss();
            return;
        }
        const action = await this.actionSheetCtrl.getTop();
        console.log("action"+action)
        if (action) {
            action.dismiss();
            return;
        }
        const popover = await this.popoverCtrl.getTop();
        console.log("popover"+popover)
        if (popover) {
            popover.dismiss();
            return;
        }
        const modal = await this.modalCtrl.getTop();
        console.log("modal"+modal)
        if (modal) {
          window['androidObj'].stopFaceCollect();
            modal.dismiss();
            return;
        }
        const isOpen = await this.menuCtrl.isOpen();
        console.log("isOpen"+isOpen)
        if (isOpen) {
            this.menuCtrl.close();
            return;
        }
        if (!this.tabsCanGoBack && !this.tabsParentCanGoBack) {
          const alert = await this.alertCtrl.create({
            header: '提示!',
            message: '确定要退出石城公证吗？',
            buttons: [
              {
                text: '取消',
                role: 'cancel',
                cssClass: 'secondary',
                handler: (blah) => {
                  console.log('Confirm Cancel: blah');
                }
              }, {
                text: '确定',
                handler: () => {
                  window['androidObj'].closeActivity();
                }
              }
            ]
          });
      
          await alert.present();
        
            return;
        }
    } catch (error) {
    }
  }


  // ngDoCheck(){
  //   if(!this.LoginInfoService.getToken()){
  //     this.loginN = false
  //   }else{
  //     this.loginN = true
  //   }
  // }
  tabchange(e){
    if(e.tab=='tab4' || e.tab=='tab3'){
      if(!!!this.LoginInfoService.getInfo().unitGuid) this.loginOut();
    }
    if(e.tab == 'tab2'){
      this.isUpdate();
    }
    this.flag=e.tab;
  }

  isUpdate() {
    // 1、获取当前应用的版本号

    this.httpService.Que_version({}).then((value: any) => {
      // console.log(this.commService.getVersionInfo())
      this.commService.getVersionInfo().subscribe(res => {
        if(value.item.appTitle !== res){
          this.appContent = value.item.appContent;
          this.isProgress = true;
          this.apkUrl = value.item.filePath;
          // this.showAlert(value.item.appContent);
        }
      });
      //2、请求服务器接口获取服务器的版本号

    }).catch(err => {
      console.log('getVersionNumber:' + err);
    });
  }

  toDownLoadAPK(){
    console.log(2222222)
    this.isProgress = false;
    this.commService.downFile(this.apkUrl);
  }

  // async showAlert(info) {

  //   //3.弹窗提示用户是否更新    
  //   const alert = await this.alertCtrl.create({
  //     header: '版本升级!',
  //     message: info,
  //     buttons: [ {
  //         text: '确认',
  //         handler: () => {
  //           //4.下载apk
  //           this.downloadApp();
  //         }
  //       }
  //     ]
  //   });
  //   await alert.present();

  // }

  // downloadApp(){
  //   //4.下载apk
  //   const targetUrl = 'https://sc.njguochu.com:46/app-debug.apk';
  //   console.log(11111111111)

  //   // console.log("++++" + JSON.stringify(this.file) );   //获取当前应用的安装（home）目录     1、应用包名称要一致   2、升级的包的版本号要大于当前应用的版本号   3、签名要一致    4、sdk 要安装

  //   // fileTransfer.download(targetUrl, this.file.dataDirectory + '石城公证.apk').then((entry) => {
  //   //   //6、下载完成调用打开应用

  //   //    this.fileOpener.open(entry.toURL(),
  //   //     'application/vnd.android.package-archive')
  //   //     .then(() => {
  //   //       console.log('File is opened')
  //   //     })
  //   //     .catch(e => {
  //   //       console.log('Error openening file', e)
  //   //     });


  //   // }, (error) => {
  //   //   alert(JSON.stringify(error));
  //   // });

  //   let that = this;
  //   //5、获取下载进度    
  //   var oProgressNum = document.getElementById('progressnum');
  //   this.isProgress = true;
  //   // fileTransfer.onProgress((event) => {
  //   //   let num = Math.ceil(event.loaded / event.total * 100);  //转化成1-100的进度
  //   //   if (num === 100) {
  //   //     oProgressNum.innerHTML = '下载完成';
  //   //     setTimeout(()=>{
  //   //       that.isProgress = false;
  //   //     },100)
  //   //   } else {
  //   //     oProgressNum.innerHTML = '下载进度：' + num + '%';

  //   //   }
  //   // });

  // }

  isShowout2(){
    this.isShow=false;
    this.LoginInfoService.setlocal('firstLoginFlag2',"4");
  }
  
  isShowout(i){
    this.next++;
    if(i=="2"){
      this.LoginInfoService.setlocal('firstLoginFlag',"2");
    }
   
  }


  async loginOut(){
 
    let modal = await this.modalController.create({
       component: LoginPage,
       mode: "md",
       cssClass: "conditions",
     });
     modal.present();
    // 模态框被关闭后回回调该方法 res 为返回值
     modal.onDidDismiss().then(res => {
       if(res.data.qrInfo=="200"){
          
       }
     })
  }
}
